﻿using Dao;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.BandedGrid;
using HospitalErpWinUI.GlobalVar;
using HospitalErpWinUI.WinFormUiHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HospitalErpWinUI.hbos.acct.acctbook.balance.itemsubj
{
    public partial class main : RibbonForm
    {
        protected DaoHelper _helper;
        DataTable _user = new DataTable();
        
        //初始化绑定默认关键词（此数据源可以从数据库取） 
        List<string> _groupsInit = new List<string>(); 
        List<string> _groupsChange = new List<string>();
        List<String> _itemsList = new List<String>();
        List<String> _itemCodeList = new List<String>();
        string[] codeArray2 = new String[] { };
        string[] valueArray2 = new String[] { };
        public main()
        {
            _helper = new DaoHelper();
            InitializeComponent();
        }

    #region 获取下拉框数据
      
        #region 获取科目数据
        private void getAcctSubj1()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_subj_specialNameForCheck";
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("acct_year", G_User.user.Acct_year);
            paramters.Add("key", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit1).Trim());

            serviceParamter.Paramters = paramters;

            List<CodeValue> objs = new List<CodeValue>();
            DataTable dt = _helper.ReadDictForSql(serviceParamter);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CodeValue codeValue = new CodeValue();
                codeValue.Code = dt.Rows[i][0].ToString();
                codeValue.Value = dt.Rows[i][1].ToString();
                objs.Add(codeValue);
            }
            searchLookUpEdit1.Properties.ValueMember = "Code";
            searchLookUpEdit1.Properties.DisplayMember = "Value";
            searchLookUpEdit1.Properties.DataSource = objs;
        }

        private void getAcctSubj2()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_subj_specialNameForCheck";
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("acct_year", G_User.user.Acct_year);
            paramters.Add("key", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit2).Trim());
            serviceParamter.Paramters = paramters;

            List<CodeValue> objs = new List<CodeValue>();
            DataTable dt = _helper.ReadDictForSql(serviceParamter);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CodeValue codeValue = new CodeValue();
                codeValue.Code = dt.Rows[i][0].ToString();
                codeValue.Value = dt.Rows[i][1].ToString();
                objs.Add(codeValue);
            }
            //    emp_code.Properties.Items.AddRange(emps);
            searchLookUpEdit2.Properties.ValueMember = "Code";
            searchLookUpEdit2.Properties.DisplayMember = "Value";
            searchLookUpEdit2.Properties.DataSource = objs;
            
        }

        // 获取科目级次
        private void getSubjLevel()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_SubLevelList";
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("acct_year", G_User.user.Acct_year);
            serviceParamter.Paramters = paramters;


            DataTable groups = _helper.ReadDictForSql(serviceParamter);
            for (int i = 0; i < groups.Rows.Count; i++)
            {
                _groupsInit.Add(groups.Rows[i][1].ToString());

            }
            comboBoxEdit1.Properties.Items.AddRange(_groupsInit);
        }

        //核算项数据
        private void getItemList()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_allCheckItem_list";
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            serviceParamter.Paramters = paramters;
            DataTable groups = _helper.ReadDictForSql(serviceParamter);
            checkedComboBoxEdit1.Properties.Items.Clear();

            CheckedListBoxItem[] itemListQuery = new CheckedListBoxItem[groups.Rows.Count + 1];
            int check = 1;
            for (int i = 0; i < groups.Rows.Count; i++)
            {
                itemListQuery[check] = new CheckedListBoxItem(groups.Rows[i][0].ToString(), groups.Rows[i][1].ToString());
                check++;

            }

            checkedComboBoxEdit1.Properties.Items.AddRange(itemListQuery);



        }


       
        //获取每个核算项数据
        private void getSelectItemList(String itemName, SearchLookUpEdit searchLookUpEdit)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_subj_checkItemActiveClass3";
            paramters.Add("table_name", itemName);
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("key", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit).Trim());
           // paramters.Add("acct_year", G_User.user.Acct_year);
            serviceParamter.Paramters = paramters;

            List<CodeValue> objs = new List<CodeValue>();
            DataTable dt = _helper.ReadDictForSql(serviceParamter);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CodeValue codeValue = new CodeValue();
                codeValue.Code = dt.Rows[i][0].ToString();
                codeValue.Value = dt.Rows[i][1].ToString();
                objs.Add(codeValue);
            }
            //    emp_code.Properties.Items.AddRange(emps);
            searchLookUpEdit.Properties.ValueMember = "Code";
            searchLookUpEdit.Properties.DisplayMember = "Value";
            searchLookUpEdit.Properties.DataSource = objs;
        
        
        
        }


        #endregion

    #endregion



        private void init() {
            //获取辅助核算
            getItemList();
            //科目字段数据赋值
            getAcctSubj1();
            getAcctSubj2();
            //初始科目级次
            getSubjLevel();
            //设置默认日期
            dateEdit1.Text = DateTime.Now.ToString("yyyy-MM-01");//本月第一天
            dateEdit2.Text = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");//本月最后一天
            
        
        
        }


        private void main_Load(object sender, EventArgs e)
        {
            init();

        }

        #region 事件


        #region 其他
        //动态创建辅助核算下拉框
        private void createItemList(String itemNames) {
            string[] itemNameArry = itemNames.Split(',');
            int i = 30;
            int j = 1;
            
            //删除动态控件
            deleteItem(_itemsList, i);



            foreach (string s in itemNameArry)
            {

                if (s.Equals("")) {
                    return;
                }
               //通过code获取value
               

               LabelControl labelControl = new LabelControl();
               SearchLookUpEdit searchLookUpEdit= new SearchLookUpEdit();

               labelControl.Name = "labelControl" + i;
               labelControl.Location = new System.Drawing.Point(20 * j, 50);
               labelControl.TabIndex = i + 1;
               labelControl.Text = s + ":";
               
                
                searchLookUpEdit.Name = "searchLookUpEdit" + i;
                searchLookUpEdit.Location = new System.Drawing.Point(labelControl.Location.X+55, 45);
                searchLookUpEdit.TabIndex = i + 1;
                searchLookUpEdit.Properties.NullText ="";
                searchLookUpEdit.Properties.ShowFooter = false;
                searchLookUpEdit.Properties.ShowClearButton = false;
                searchLookUpEdit.EditValueChanged += new System.EventHandler(searchLookUpEdit_EditValueChange);
                //searchLookUpEdit.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(searchLookUpEdit_ButtonClick);
               // searchLookUpEdit.EditValue = "000000";
                panelControl2.Controls.Add(labelControl);
                panelControl2.Controls.Add(searchLookUpEdit);

                
                getSelectItemList(s.Trim(), searchLookUpEdit);

               
                i++;
                j = j + 10;

            }

            _itemsList.Clear();

            foreach (string s in itemNameArry)
            {
                _itemsList.Add(s);
            }
                   
        }

        //删除控件
        private void deleteItem(List < String > _itemsList,int i)
        {
            for (int j = i; j <=_itemsList.Count()+i;j++ )
            {
                panelControl2.Controls.RemoveByKey("searchLookUpEdit" + j);

                panelControl2.Controls.RemoveByKey("labelControl" + j);

            }

         }

       
        #endregion


        private void repositoryItemHyperLinkEdit1_Click(object sender, EventArgs e)
        {

        }

    

        private void checkedComboBoxEdit1_TextChanged(object sender, EventArgs e)
        {
            codeArray2 = checkedComboBoxEdit1.EditValue.ToString().Trim().Split(',');
            valueArray2 = checkedComboBoxEdit1.Text.ToString().Trim().Split(',');
            createItemList(checkedComboBoxEdit1.Text.ToString().Trim());

        }




        #endregion
       

        private void acct_acctbook_balance_item_subj_Click(object sender, EventArgs e)
        {
            try
            {
                Query();
            }
            catch (Exception ex)
            {
                MessageForm.Exception(ex.Message);
            }
        }


        private void searchLookUpEdit_EditValueChange(object sender, EventArgs e)
        {
            SearchLookUpEdit searchLookUpEdit = sender as SearchLookUpEdit;
            MessageBox.Show(searchLookUpEdit.EditValue.ToString());

            if (searchLookUpEdit.EditValue.ToString().Trim()!= "" || searchLookUpEdit.EditValue.ToString().Trim() != null)
            {
                _itemCodeList.Add(searchLookUpEdit.EditValue.ToString().Trim());
            }
           

        }

        //封装动态辅助核算参数
        //checkedComboBoxEdit1.EditValue.ToString().Trim()、checkedComboBoxEdit1.Text.ToString().Trim()
        private String getItemParas()
        {
            string[] codeArray = checkedComboBoxEdit1.EditValue.ToString().Trim().Split(','); //checkedComboBoxEdit1.EditValue.ToString().Trim().Split(",");
            string[] valueArray = checkedComboBoxEdit1.Text.ToString().Trim().Split(',');
            int i = 0;
            int j = 0;
            int k = _itemCodeList.Count;
            int g = _itemsList.Count;
            //MessageBox.Show(k.ToString());
            //MessageBox.Show(g.ToString());
            //删除上一次动态创建的控件信息，只保留本次动态创建的控件信息
            _itemCodeList.RemoveRange(0, k-g);

            

            String para = "";
            foreach (String code in codeArray)
            {
                if (j <= k)
                {
                    para = para + "<tr><key>" + code.Trim() + "</key><keyname>" + valueArray[i].Trim() + "</keyname><value>" + _itemCodeList[j] + "</value><valueB></valueB><valueE></valueE></tr>";

                }
                else
                {
                    para = para + "<tr><key>" + code.Trim() + "</key><keyname>" + valueArray[i].Trim() + "</keyname><value></value><valueB></valueB><valueE></valueE></tr>";
                }
                i++;
                j++;
            }
            para = "<root>" + para + "</root>";
            return para;
        }

        #region 创建动态表

        // 创建bandedGridColumn列的方法 
        private void CreateGridColumn()
        {
            BandedGridView view = this.bandedGridView1;
            view.BeginUpdate(); //开始视图的编辑，防止触发其他事件
            view.BeginDataUpdate(); //开始数据的编辑
            view.Bands.Clear();
            view.Columns.Clear();


            GridBand acctSubjCode = view.Bands.AddBand("科目编码");
            acctSubjCode.Columns.Add(createStaticColumn("科目编码", "acct_subj_code", true));
            acctSubjCode.MinWidth = 100;

            GridBand acctSubjName = view.Bands.AddBand("科目编码");
            acctSubjName.Columns.Add(createStaticColumn("科目编码", "acct_subj_name", true));
            acctSubjName.MinWidth = 100;

            if (FormHelper.GetValueForCheckEdit(checkEdit2).Trim() == "1")
            {
                GridBand band2 = view.Bands.AddBand("年初余额");
                GridBand band2J = band2.Children.AddBand("借方");
                GridBand band2D = band2.Children.AddBand("贷方");

                band2J.Columns.Add(createStaticColumn("借方", "bal_os_y", true));
                band2D.Columns.Add(createStaticColumn("贷方", "bal_cs_y", true));

            }
            GridBand band3 = view.Bands.AddBand("期初余额");
            GridBand band3J = band3.Children.AddBand("借方");
            GridBand band3D = band3.Children.AddBand("贷方");
            band3J.Columns.Add(createStaticColumn("借方", "bal_os", true));
            band3D.Columns.Add(createStaticColumn("贷方", "bal_cs", true));


            GridBand band4 = view.Bands.AddBand("本期发生额");
            GridBand band4J = band4.Children.AddBand("借方");
            GridBand band4D = band4.Children.AddBand("贷方");
            band4J.Columns.Add(createStaticColumn("借方", "amt_debit", true));
            band4D.Columns.Add(createStaticColumn("贷方", "amt_credit", true));




            if (FormHelper.GetValueForCheckEdit(checkEdit1).Trim() == "1")
            {
                GridBand band5 = view.Bands.AddBand("本年累计");
                GridBand band5J = band5.Children.AddBand("借方");
                GridBand band5D = band5.Children.AddBand("贷方");
                band5J.Columns.Add(createStaticColumn("借方", "sum_od", true));
                band5D.Columns.Add(createStaticColumn("贷方", "sum_oc", true));
            }
            GridBand band6 = view.Bands.AddBand("期末余额");
            GridBand band6J = band6.Children.AddBand("借方");
            GridBand band6D = band6.Children.AddBand("贷方");
            band6J.Columns.Add(createStaticColumn("借方", "amt_debit2", true));
            band6D.Columns.Add(createStaticColumn("贷方", "amt_credit2", true));

            GridBand band7 = view.Bands.AddBand("是否包含年初");
            band7.Columns.Add(createStaticColumn("是否包含年初", "this_year", true));
            band7.Visible = false;

            GridBand band8 = view.Bands.AddBand("是否包含本年");
            band8.Columns.Add(createStaticColumn("是否包含本年", "theyear", true));
            band8.Visible = false;
            GridBand band9 = view.Bands.AddBand("is_check");
            band9.Columns.Add(createStaticColumn("is_check", "is_check", true));
            band9.Visible = false;


    

            ///循环对齐表头
            for (int i = 0; i < this.bandedGridView1.Columns.Count; i++)
            {
                this.bandedGridView1.Columns[i].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;//表头居中对齐
            }

            ///循环对齐BandedGridView控件的GridBand控件 表头
            for (int i = 0; i < this.bandedGridView1.Bands.Count; i++)
            {
                this.bandedGridView1.Bands[i].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;//居中对齐
            }

            view.EndDataUpdate();//结束数据的编辑
            view.EndUpdate();   //结束视图的编辑
            view.OptionsView.ShowGroupPanel = false;
            view.OptionsView.ShowColumnHeaders = false;


        }

        private BandedGridColumn createStaticColumn(String caption, String FieldName, Boolean visible)
        {
            var bandedGridColumn = new BandedGridColumn();
            bandedGridColumn.Caption = caption;
            bandedGridColumn.FieldName = FieldName;
            bandedGridColumn.Visible = visible;
           // bandedGridColumn.VisibleIndex = visibleIndex;

            return bandedGridColumn;
        }



        #endregion
        #region 主查询
        private void Query()
        {
            CreateGridColumn();
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_acctbook_balance_item_subj";

            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("acct_year", G_User.user.Acct_year);
            paramters.Add("start_time", dateEdit1.DateTime.ToString("yyyy-MM-dd"));
            paramters.Add("end_time", dateEdit2.DateTime.ToString("yyyy-MM-dd"));
            paramters.Add("theyear", FormHelper.GetValueForCheckEdit(checkEdit2).Trim());
            paramters.Add("this_year", FormHelper.GetValueForCheckEdit(checkEdit1).Trim());
            paramters.Add("subj_level", FormHelper.GetValueForComboBoxEdit(comboBoxEdit1).Trim());
            paramters.Add("start_subj", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit1).Trim());
            paramters.Add("end_subj", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit2).Trim());
            paramters.Add("is_acc", FormHelper.GetValueForCheckEdit(checkEdit3).Trim());
            paramters.Add("is_cancel", FormHelper.GetValueForCheckEdit(checkEdit4).Trim());
            paramters.Add("curr_code", "RMB");
            paramters.Add("subjCheckItems", getItemParas());

            //  paramters.Add("sub_type_code", strArray2[0]);


            //DateTime.Parse("2016-3-16 12:12:12")

            serviceParamter.Paramters = paramters;

            DataTable dt = _helper.ReadSqlForDataTable(serviceParamter);
            dt.Columns.Add("checked", System.Type.GetType("System.Boolean"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["checked"] = "false";
            }
            _user = dt;
            gridControl1.DataSource = _user;

        }
        #endregion

        private void searchLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
          
                //getAcctSubj1();
            }
            catch (Exception ex)
            {
                MessageForm.Exception(ex.Message);

            }
        }

        private void searchLookUpEdit2_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
    
               // getAcctSubj2();
            }
            catch (Exception ex)
            {
                MessageForm.Exception(ex.Message);

            }
        }

        private void searchLookUpEdit1_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            searchLookUpEdit1.EditValue = "";
        }

        private void searchLookUpEdit2_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            searchLookUpEdit2.EditValue = "";
        }
       /* private void searchLookUpEdit_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            SearchLookUpEdit searchLookUpEdit = sender as SearchLookUpEdit;
            searchLookUpEdit.EditValue = "";
            getSelectItemList(searchLookUpEdit.EditValue.ToString().Trim(), searchLookUpEdit);
        }
        */
    }
}
